<template>
    <div class="table">
        <el-breadcrumb separator="/" class="breadCrumb">
            <el-breadcrumb-item>{{$t('sidebar.taskCronerMsg')}}</el-breadcrumb-item>
            <el-breadcrumb-item>{{$t('sidebar.taskCronerConfig')}}</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="crumbs">
            <el-row :gutter="15">
                <el-col :span="2" style="min-width:100px;">
                    <el-input
                        :placeholder="$t('taskCronerConfig.pleaseInput',{ name: 'ID' })"
                        v-model="searchForm.id">
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-input
                        :placeholder="$t('taskCronerConfig.pleaseInput',{ name: $t('taskCronerConfig.taskClass') })"
                        v-model="searchForm.taskClass">
                    </el-input>
                </el-col>
                <el-col :span="4" style="line-height: 35px;">
                    <el-button size="small" type="primary" @click="searchData()">{{$t('taskCronerConfig.search')}}</el-button>
                    <el-button size="small" type="primary" @click="refreshData()">{{$t('taskCronerConfig.refresh')}}</el-button>
                </el-col>
                <el-col :span="1" class="floatRight">
                    <el-button size="small" type="primary" @click="addButton()">{{$t('taskCronerConfig.add')}}</el-button>
                </el-col>
            </el-row>
        </div>
        <el-table :data="tableData" border style="width: 100%" :max-height="$store.state.allTable.tableHeight" v-loading="tableDataLoading"
                  :element-loading-text="$t('allTable.dataLoading')">
            <el-table-column prop="id" label="ID" width="40" fixed>
            </el-table-column>
            <el-table-column prop="taskName" :label="$t('taskCronerConfig.taskName')" min-width="80">
                <template scope="scope">
                    <el-popover trigger="hover" placement="top">
                        <!--<p>{{ $t('taskCronerConfig.taskDesc') }}</p>-->
                        <p>{{ scope.row.taskDesc }}</p>
                        <div slot="reference" class="name-wrapper">
                            <p>{{ scope.row.taskName }}</p>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column prop="taskClass" :label="$t('taskCronerConfig.taskClass')" min-width="150">
            </el-table-column>
            <el-table-column :label="$t('taskCronerConfig.taskOwner')" width="100">
                <template scope="scope">
                    <el-button size="mini" v-for="(value,index) in scope.row.taskOwner" @click="showContact(index)">{{ value }}</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="cron" :label="$t('taskCronerConfig.cron')" width="100">
            </el-table-column>
            <el-table-column prop="runType" :label="$t('taskCronerConfig.runType')" width="80" :formatter="runTypeShow">
            </el-table-column>
            <el-table-column prop="runTarget" :label="$t('taskCronerConfig.runTarget')" width="80">
            </el-table-column>
            <el-table-column prop="nextRunDate" :label="$t('taskCronerConfig.nextRunDate')" width="150">
            </el-table-column>
            <el-table-column :label="$t('taskCronerConfig.statsStartDate')" width="80">
                <template scope="scope">
                    <span>{{scope.row.statsStartDate}}</span>
                    <el-button size="mini"
                               @click="emptyStatistics(scope.row.id)">{{$t('taskCronerConfig.reset')}}</el-button>
                </template>
            </el-table-column>
            <el-table-column :label="$t('taskCronerConfig.statsTimes')" width="150">
                <template scope="scope">
                    <p>{{`${scope.row.statsAll}/${scope.row.statsFailAll}/${scope.row.statsFailProgram}/${scope.row.statsFailPartner}`}}</p>
                </template>
            </el-table-column>
            <el-table-column :label="$t('taskCronerConfig.statsMillisecond')" width="120">
                <template scope="scope">
                    <p>{{`${scope.row.statsTimeAll}/${scope.row.statsTimeWait}/${scope.row.statsTimeRun}`}}</p>
                </template>
            </el-table-column>
            <el-table-column prop="createDate" :label="$t('taskCronerConfig.createDate')" width="80">
            </el-table-column>
            <el-table-column prop="modifyDate" :label="$t('taskCronerConfig.modifyDate')" width="80">
            </el-table-column>
            <el-table-column prop="status" :label="$t('taskCronerConfig.status')" width="60" :formatter="statusShow">
            </el-table-column>
            <el-table-column :label="$t('taskCronerConfig.operation')" width="100" fixed="right">
                <template scope="scope">
                    <el-button size="mini"
                               @click="handleEdit(scope)">{{$t('taskCronerConfig.edit')}}</el-button>
                    <el-button size="mini" type="danger"
                               @click="deleteData(scope.row.id)">{{$t('taskCronerConfig.delete')}}</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="mgtb20" :class="{ pagination : tableData.length !== 0}">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change ="handleCurrentChange"
                :page-sizes="$store.state.allTable.pageSizesChoice"
                :page-size="pageSizeGetter"
                layout="total, sizes, prev, pager, next, jumper"
                :total="sizeAll"
                :page-count="pageCount"
                v-if="tableData.length !== 0">
            </el-pagination>
        </div>
        <el-dialog :title="$t('sidebar.taskCronerConfig')" size="small" v-model="dialogFormVisible">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" :inline="true" label-position="right">
                <el-row type="flex">
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.taskName')" prop="taskName">
                            <el-input v-model="ruleForm.taskName" :placeholder="$t('taskCronerConfig.taskName')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.taskClass')" prop="taskClass">
                            <el-input v-model="ruleForm.taskClass" :placeholder="$t('taskCronerConfig.taskClass')" :readonly="hasTaskClass"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col>
                        <el-popover
                            ref="popover1"
                            v-model="popoverTaskOwner"
                            placement="bottom"
                            :title="$t('taskCronerConfig.taskOwner')"
                            trigger="click">
                            <i class="el-icon-close popoverClose" @click="popoverTaskOwner = false"></i>
                            <el-transfer
                                filterable
                                v-model="choiceTaskOwner"
                                :data="failLinkData"
                                :titles="['未选', '已选']"></el-transfer>
                        </el-popover>
                        <el-form-item :label="$t('taskCronerConfig.taskOwner')">
                            <!--<el-input v-model="ruleForm.taskOwner" :placeholder="$t('taskCronerConfig.taskOwner')"></el-input>-->
                            <el-tag v-for="value in choiceTaskOwner" class="linkTag" type="primary">{{value}}</el-tag>
                            <el-button size="mini" v-popover:popover1 @click="contactList.length === 0?getContact():'';">修改</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.taskDesc')" prop="taskDesc">
                            <el-input type="textarea" v-model="ruleForm.taskDesc" :placeholder="$t('taskCronerConfig.taskDesc')"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.cron')" prop="cron">
                            <el-input v-model="ruleForm.cron" :placeholder="$t('taskCronerConfig.cron')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.runType')" prop="runType">
                            <!--<el-input v-model="ruleForm.runType" :placeholder="$t('taskCronerConfig.runType')"></el-input>-->
                            <el-select v-model="ruleForm.runType" :placeholder="$t('taskCronerConfig.runType')">
                                <el-option
                                    key="1"
                                    label="全局唯一"
                                    value="1">
                                </el-option>
                                <el-option
                                    key="0"
                                    label="任意执行"
                                    value="0">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.runTarget')" prop="runTarget">
                            <!--<el-input v-model="ruleForm.runTarget" :placeholder="$t('taskCronerConfig.runTarget')"></el-input>-->
                            <el-autocomplete
                                class="inline-input"
                                v-model="ruleForm.runTarget"
                                :fetch-suggestions="querySearch"
                                placeholder="请输入内容"
                                @select="handleSelect"
                            ></el-autocomplete>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">{{$t('taskCronerConfig.cancel')}}</el-button>
                <el-button type="primary" @click="addData('ruleForm')">{{$t('taskCronerConfig.confirm')}}</el-button>
            </div>
        </el-dialog>
        <el-dialog title="报警联系人" size="tiny" v-model="dialogContact">
            <el-form :model="contactForm" label-width="100px">
                <el-row type="flex">
                    <el-col>
                        <el-form-item label="ID">
                            <el-input v-model="contactForm.id" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.contactName')">
                            <el-input v-model="contactForm.contactName" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.contactType')">
                            <el-input v-model="contactForm.contactType" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.mobile')">
                            <el-input v-model="contactForm.mobile" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.email')">
                            <el-input v-model="contactForm.email" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.weixin')">
                            <el-input v-model="contactForm.weixin" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col>
                        <el-form-item :label="$t('taskCronerConfig.qq')">
                            <el-input v-model="contactForm.qq" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col></el-col>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
    import { mapGetters,mapMutations } from 'vuex';
    import common from '../../assets/script/common';
    import { isChinese } from '../../assets/script/validate';
    export default {
        data() {
            const validateRunTarget = (rule, value, callback) => {
                if (this.configNames.indexOf(value) === -1) {
                    callback(new Error(this.$i18n.t('taskCronerConfig.validateRunTarget')));
                } else {
                    callback();
                }
            };
            const validateCron = (rule, value, callback) => {
                if (isChinese(value)) {
                    callback(new Error(this.$i18n.t('taskCronerConfig.validateCron')));
                } else {
                    callback();
                }
            };
            return {
                tableData:[],
                pageName:'taskAlertContact',
                pageCount:1,
                sizeAll:0,
                dialogFormVisible: false,
                dialogContact: false,
                contactForm: {},
                searchForm:{
                    id:'',
                    taskClass:''
                },
                ruleForm: {
                    id:'',
                    createDate: '',
                    modifyDate: '',
                    cron: '',
                    nextRunDate:'',
                    runTarget:'',
                    runType:'',
                    statsAll:'',
                    statsFailAll:'',
                    statsFailPartner:'',
                    statsFailProgram:'',
                    statsStartDate:'',
                    statsTimeAll:'',
                    statsTimeRun:'',
                    status:'',
                    taskName:'',
                    taskClass: '',
                    taskDesc: '',
                    taskOwner: ''
                },
                rules: {
                    cron: [
                        { required: true, message: this.$i18n.t('taskCronerConfig.pleaseInput',{ name: this.$i18n.t('taskCronerConfig.cron') }), trigger: 'change' },
                        { required: true, trigger: 'change', validator: validateCron}
                    ],
                    nextRunDate: [
                        { required: true, message: this.$i18n.t('taskCronerConfig.pleaseInput',{ name: this.$i18n.t('taskCronerConfig.nextRunDate') }), trigger: 'blur' }
                    ],
                    runType: [
                        { required: true, message: this.$i18n.t('taskCronerConfig.pleaseInput',{ name: this.$i18n.t('taskCronerConfig.runType') }), trigger: 'blur' }
                    ],
                    runTarget: [
                        { required: true, message: this.$i18n.t('taskCronerConfig.pleaseInput',{ name: this.$i18n.t('taskCronerConfig.runTarget') }), trigger: 'blur' },
                        { required: true, trigger: 'change', validator: validateRunTarget}
                    ],
                    taskClass: [
                        { required: true, message: this.$i18n.t('taskCronerConfig.pleaseInput',{ name: this.$i18n.t('taskCronerConfig.taskClass') }), trigger: 'blur' }
                    ],
                    taskName: [
                        { required: true, message: this.$i18n.t('taskCronerConfig.pleaseInput',{ name: this.$i18n.t('taskCronerConfig.taskName') }), trigger: 'blur' }
                    ],
                    taskDesc: [
                        { required: true, message: this.$i18n.t('taskCronerConfig.pleaseInput',{ name: this.$i18n.t('taskCronerConfig.taskDesc') }), trigger: 'blur' }
                    ],
                    taskOwner: [
                        { required: true, message: this.$i18n.t('taskCronerConfig.pleaseInput',{ name: this.$i18n.t('taskCronerConfig.taskOwner') }), trigger: 'blur' }
                    ]
                },
                hasTaskClass: true,
                dialogType:'',
                searchId:'',
                searchClass:'',
                contactList:[],
                choiceTaskOwner:[],
                failLinkData:[],
                restaurants: [],
                configNames: [],
                tableDataLoading:true,
                popoverTaskOwner:false
            }
        },
        created() {
            if(this.tableData.length === 0){
                console.log(this.tableData);
                this.getData(1,this.$store.state.allTable.pageSize);
            }
        },
        computed:{
            ...mapGetters([
                "pageSizeGetter",
            ]),
        },
        methods:{
            ...mapMutations([
                'pageSizeMutation'
            ]),
            querySearch(queryString, cb) {
                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
                cb(results);
            },
            createFilter(queryString) {
                return (restaurant) => {
                    return (restaurant.value.indexOf(queryString.toLowerCase()) === 0);
                };
            },
            handleSelect(item) {
                console.log(item);
            },
            getTaskHost() {
                let self = this;
                common.getAjax(self,'/api/taskHostConfigs', 1, {id:''}, (res) => {
                    if(res.data.status === 401){
                        common.refreshToken(self, (token) => {
                            sessionStorage.setItem("token",token);
                            self.getTaskHost();
                        });
                    }else{
                        res.data.results.forEach((value,index) => {
                            if(value.configName){
                                self.restaurants.push({'value':value.configName});
                                self.configNames.push(value.configName);
                            }
                        });
                        console.log(self.restaurants);
                    }
                });
            },
            getContact() {
                let self = this;
                let __data = [];
                common.getAjax(self,'/api/taskAlertContacts', 1, {id:''}, (res) => {
                    if(res.data.status === 401){
                        common.refreshToken(self, (token) => {
                            sessionStorage.setItem("token",token);
                            self.getContact();
                        });
                    }else{
                        self.contactList = res.data.results;
                        self.contactList.forEach((value,index) => {
                            __data.push({
                                key: value.contactName,
                                label: value.contactName
                            });
                        });
                        self.failLinkData = __data;
                    }
                });
            },
            showContact(_id) {
                _id = JSON.parse(_id);
                let self = this;
                common.searchTableList(self, 'taskAlertContact', _id, (data) => {
                    if(data.id !== undefined){
                        self.contactForm = data;
                        self.dialogContact = true;
                    }
                });
            },
            contactSure() {
                let self = this;
                let Obj1 = {};
                let index = 0,len = self.contactList.length;
                self.contactList.forEach((value,index) => {
                    index++;
                    if(self.choiceTaskOwner.indexOf(value.contactName) !== -1) {
                        Obj1[value.id] = value.contactName;
                    }
                    if(index === len){
                        self.ruleForm.taskOwner = JSON.stringify(Obj1);
                    }
                });
            },
            handleSizeChange(val) {
                let self = this;
                self.pageSizeMutation(val);
                self.getData(1,self.$store.state.allTable.pageSize);
            },
            handleCurrentChange(val) {
                common.changePageGoToTop(this,val);
            },
            getData(_pageSize,_pageNum) {
                let self = this;
                self.tableDataLoading = true;
                common.getTableList(self, 'taskCronerConfig', _pageSize, _pageNum, self.searchForm, (data) => {
                    self.tableData = data.results ? data.results : [];
                    self.pageCount = data.pageCount;
                    self.sizeAll = data.sizeAll;
                    self.tableDataLoading = false;
                });
            },
            addData(formName) {
                let self = this;
                let __token = sessionStorage.getItem("token");
                let __ruleForm = this.ruleForm;

                this.$refs[formName].validate((valid) => {
                    if(valid){
                        self.contactSure();
                        if(this.dialogType === 'add'){
                            common.postTableList(self, 'taskCronerConfig', __ruleForm, () => {
                                self.getData(1,self.$store.state.allTable.pageSize);
                                this.dialogFormVisible = false;
                                this.hasTaskClass = true;
                                for(let key in __ruleForm){
                                    __ruleForm[key] = '';
                                }
                                this.ruleForm = __ruleForm;
                            });
                        }else if(this.dialogType === 'edit'){
                            common.putTableList(self, 'taskCronerConfig', __ruleForm, () => {
                                self.getData(1,self.$store.state.allTable.pageSize);
                                this.dialogFormVisible = false;
                                this.hasTaskClass = true;
                                for(let key in __ruleForm){
                                    __ruleForm[key] = '';
                                }
                                this.ruleForm = __ruleForm;
                            });
                        }

                    }
                });
            },
            deleteData(_id) {
                let self = this;
                common.deleteTableList(self, 'taskCronerConfig', _id, () => {
                    self.getData(1,self.$store.state.allTable.pageSize);
                })
            },
            handleEdit(scopes) {
                let self = this;
                let __ruleForm = this.ruleForm;
                if(!self.restaurants.length){
                    self.getTaskHost();
                }
                this.hasTaskClass = true;
                for(let key in __ruleForm){
                    if(scopes.row[key] != null){
                        __ruleForm[key] = scopes.row[key].toString();
                    }else {
                        __ruleForm[key] = '';
                    }
                }
                self.choiceTaskOwner=Object.values(scopes.row.taskOwner);
                self.ruleForm = __ruleForm;
                self.dialogFormVisible = true;
                self.dialogType = 'edit';
            },
            searchData() {
                let self = this;
                self.getData(1,self.$store.state.allTable.pageSize);
            },
            refreshData() {
                let self = this;
                for(let key in self.searchForm){
                    self.searchForm[key] = '';
                }
                self.getData(1,self.$store.state.allTable.pageSize);
            },
            addButton() {
                let self = this;
                let __ruleForm = self.ruleForm;
                if(!self.restaurants.length){
                    self.getTaskHost();
                }
                for(let key in __ruleForm){
                    __ruleForm[key] = '';
                }
                self.choiceTaskOwner=[];
                self.dialogFormVisible = true;
                self.dialogType = 'add';
                self.hasTaskClass = false;
            },
            statusShow(row, column) {
                if(row.status === 1)
                    return "正常";
            },
            runTypeShow(row, column) {
                if(row.runType === 1)
                    return "全局唯一";
                else
                    return "任意执行";
            },
            emptyStatistics(_id) {
                let self = this;
                self.ruleForm.id = _id;
                common.postTableList(self,'taskCronerConfig/resetStats',self.ruleForm,() => {
                    self.$message({
                        message: self.$i18n.t('taskCronerConfig.resetNotify'),
                        type: 'success'
                    });
                    self.getData(1,this.$store.state.allTable.pageSize);
                },() => {
                    self.emptyStatistics(_id);
                });
            }
        }
    }
</script>
<style lang="stylus">

</style>
